package com.kl.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.kl.config.CurrentLock;
import com.kl.domain.FreightDTO;
import com.kl.em.ConstantEnum;
import com.kl.em.Result;
import com.kl.entity.Freight;
import com.kl.entity.Quan;
import com.kl.feign.FreightServiceFeign;
import com.kl.service.IFreightService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Objects;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2021-10-29
 */
@RestController
@RequestMapping("/freight")
@Api(value = "后台物价(运费)管理接口")
public class FreightController {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private CurrentLock lock;

    @Autowired
    private IFreightService freightService;


    @ApiOperation(value = "查询所有物价详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNumber", value = "第几页", required = true, paramType = "path"),
            @ApiImplicitParam(name = "pageSize", value = "每页几条", required = true, paramType = "path")
    })
    @GetMapping("/{pageNumber},/{pageSize}")
    public Result<List<FreightDTO>> findAll(@PathVariable("pageNumber") Integer pageNumber, @PathVariable("pageSize") Integer pageSize) {
        Page<Freight> page = new Page<>(pageNumber, pageSize, false);
        IPage<Freight> iPage = freightService.page(page);
        List<Freight> list = iPage.getRecords();
        String s = JSONObject.toJSONString(list);
        List<FreightDTO> freightDTOS = JSONObject.parseArray(s, FreightDTO.class);
        return Result.build(ConstantEnum.SUCCESS).setResult(freightDTOS);
    }


    @ApiOperation(value = "修改物价详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "freight", value = "实体类", required = true, paramType = "body"),
    })
    @PutMapping
    public Result update(@RequestBody Freight freight) {
        freightService.updateById(freight);
        return Result.build(ConstantEnum.SUCCESS);
    }

    @ApiOperation(value = "增加物价详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "freight", value = "实体类", required = true, paramType = "body")
    })
    @PostMapping
    public Result add(@RequestBody FreightDTO FreightDTO) {
        //FreightDTO dto = new FreightDTO();
        // freightServiceFeign.add(dto);
        String s = JSONObject.toJSONString(FreightDTO);
        Freight freight = JSONObject.parseObject(s, Freight.class);
        freightService.save(freight);
        System.out.println("1111111111111111111");
        return Result.build(ConstantEnum.SUCCESS);
    }


    @ApiOperation(value = "根据id删除物价详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "path")
    })
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") Integer id) {
        freightService.removeById(id);
        return Result.build(ConstantEnum.SUCCESS).setResult("删除");
    }

    @ApiOperation(value = "根据id和重量得出价格")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "quest"),
            @ApiImplicitParam(name = "volume", value = "m³", required = true, paramType = "quest"),
            @ApiImplicitParam(name = "kg", value = "kg", required = true, paramType = "quest")
    })
    @GetMapping("/getPrice")
    public Result getPrice(@RequestParam Integer id,@RequestParam Integer volume,@RequestParam Integer kg) {
        Freight freight = freightService.getById(id);
        //kg - 起重  × 续重单价 + qijia
        int f;
        if(kg>freight.getFirstWeight()){
            int  kg2 = (kg - freight.getFirstWeight().intValue());
            double  i2 =  kg2/freight.getRemarks();
            double ceil = Math.ceil(i2);
            int ceil2 = new Double(ceil).intValue();
            int cp = freight.getContinuedPrice().intValue();
            int cp2= cp*ceil2;
            f = freight.getStartingPrice().intValue()+cp2;
        }else {
            f=freight.getStartingPrice().intValue();
        }
        if(volume>1){
            double ceil1 = Math.ceil(volume / 1);
            int vp = new Double(ceil1).intValue();
            int p = vp*freight.getVolumePrice();
            f=f+p;
        }

        return Result.build(ConstantEnum.SUCCESS).setResult(f);
    }


    @ApiOperation(value = "1")
    @PostMapping("/seckill")
    public Result seckill(){
        String value = String.valueOf(new Date().getTime()+5000);
        //枷锁
        boolean lock = this.lock.lock("key",value);
        if(lock){
            /*//抢到锁,执行库存减逻辑
            //Quan q = (Quan)redisTemplate.boundHashOps("q").get("1");
            String o =(String) redisTemplate.boundValueOps(1).get();
            System.out.println(o);
            if(Integer.parseInt(o)<=0){//是否已经卖完
                return Result.build(ConstantEnum.ERROR).setResult("卖光了");
            }
            Long decrement = redisTemplate.boundValueOps(1).decrement();
            System.out.println(decrement);
            if(decrement<=0){//是否刚好卖完最后一个
                return Result.build(ConstantEnum.SUCCESS).setResult("卖空了");
            }
            Quan quan = new Quan();
            quan.setId(1L);
            quan.setName("满减");
            quan.setCount(Integer.parseInt(decrement.toString()));
            System.out.println(decrement);
            redisTemplate.boundHashOps("q").put(quan.getId(),quan);*/

            this.lock.unlock("key",value);

            return Result.build(ConstantEnum.SUCCESS).setResult(lock);
        }
        return Result.build(ConstantEnum.ERROR).setResult(lock);
    }
    @ApiOperation(value = "2")
    @PostMapping("/setRedis")
    public Result setRedis(){
        Quan quan = new Quan();
        quan.setId(1L);
        quan.setCount(10);
        quan.setName("满减");
        redisTemplate.boundHashOps("q").put(quan.getId(),quan);
        redisTemplate.boundValueOps(quan.getId()).set(quan.getCount().toString());
        return Result.build(ConstantEnum.SUCCESS);
    }


}